// src/components/popups/adminEditPermission/UserList.tsx

import { useEffect, useState, useCallback } from 'react';
import type { FC } from 'react';
import type { EditableUser } from '@/types/types';
import EditPermission from '@/components/popups/adminEditPermission/EditPermission';
import { fetchAllUsers } from '@/services/PermissionService';

const UserList: FC<{ onClose: () => void }> = ({ onClose }) => {
  const [editableUsers, setEditableUsers] = useState<EditableUser[]>([]);
  const [selectedUser, setSelectedUser] = useState<EditableUser | null>(null);
  const [page, setPage] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const limit = 5;

  const loadUsers = useCallback(async () => {
    setLoading(true);
    setError('');
    setTimeout(async () => {
      try {
        const skip = page * limit;
        const newUsers = await fetchAllUsers(skip, limit);
        setEditableUsers(newUsers);
      } catch (err: unknown) {
        const errorMessage = err instanceof Error ? err.message : 'Failed to load users.';
        setError(errorMessage);
      } finally {
        setLoading(false);
      }
    }, 300);
  }, [page, limit]);

  useEffect(() => {
    loadUsers();
  }, [loadUsers]);

  const groupPermissions = (ids: number[]): string[] => {
    const has = (id: number) => ids.includes(id);
    const result: string[] = [];

    // Scholars Dashboard permissions
    if (has(1)) result.push(`Scholars Dashboard: ${has(2) ? 'View & Edit' : 'View'}`);
    if (has(9)) result.push('Scholars Dashboard: None');

    // Sponsors Dashboard permissions
    if (has(3)) result.push(`Sponsors Dashboard: ${has(4) ? 'View & Edit' : 'View'}`);
    if (has(10)) result.push('Sponsors Dashboard: None');

    // Scholars Reports permissions
    if (has(5)) result.push(`Scholars Reports: ${has(6) ? 'View & Export' : 'View'}`);
    if (has(11)) result.push('Scholars Reports: None');

    // Sponsors Reports permissions
    if (has(7)) result.push(`Sponsors Reports: ${has(8) ? 'View & Export' : 'View'}`);
    if (has(12)) result.push('Sponsors Reports: None');

    return result;
  };

  const handlePermissionUpdate = async () => {
    await loadUsers();
  };

  return (
    <div
      className="fixed inset-0 z-[1000] flex items-center justify-center bg-black/60 dark:bg-black/80 backdrop-blur-sm p-1 sm:p-6 font-poppins"
      onClick={() => {
        if (!selectedUser) onClose();
      }}
    >
      <div
        className="relative w-full max-w-4xl w-[98%] max-h-[80vh] overflow-y-auto bg-white dark:bg-slate-900 rounded-3xl shadow-2xl dark:shadow-blue-900 animate-fade-in-up border border-gray-100 dark:border-slate-800"
        onClick={e => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-4 sm:px-8 py-4 sm:py-6 bg-white dark:bg-slate-900 flex justify-between items-center border-b border-gray-200 dark:border-slate-800 rounded-t-3xl shadow-sm">
          <h2 className="text-xl sm:text-2xl font-extrabold text-blue-700 dark:text-cyan-300 tracking-tight">Manage User Permissions</h2>
          <button onClick={onClose} className="absolute right-3 top-3 w-10 h-10 flex items-center justify-center text-gray-500 dark:text-gray-300 text-2xl font-bold rounded-full hover:bg-red-50 dark:hover:bg-red-900 hover:text-red-600 dark:hover:text-red-300 transition">
            ×
          </button>
        </div>
        {/* Content */}
        <div className="p-1 sm:p-6 space-y-4 text-xs sm:text-base text-gray-800 dark:text-gray-100">
          {/* Loading */}
          {loading && (
            <div className="flex justify-center py-64">
              <div className="flex items-center gap-3">
                <div className="w-5 h-5 border-2 border-blue-500 dark:border-cyan-400 border-t-transparent rounded-full animate-spin" />
                <span className="text-blue-600 dark:text-cyan-300 font-medium">Loading users...</span>
              </div>
            </div>
          )}
          {/* Error */}
          {error && <p className="text-red-500 dark:text-red-400 text-center">{error}</p>}
          {/* Table */}
          {!loading && !error && (
            <div className="animate-fade-in transition-opacity duration-300">
              {/* Horizontal scroll hint for mobile */}
              <div className="block sm:hidden text-center text-gray-400 dark:text-gray-500 text-xs mb-2">Swipe left/right to see more</div>
              <div className="overflow-x-auto rounded-xl border border-gray-200 dark:border-slate-700 bg-white dark:bg-slate-900">
                <table className="min-w-[600px] w-full text-left text-xs sm:text-sm">
                  <thead className="bg-blue-50 dark:bg-slate-800 text-gray-700 dark:text-cyan-300 sticky top-0 z-10 border-b-2 border-gray-200 dark:border-slate-700">
                    <tr>
                      <th className="px-4 py-3 whitespace-nowrap font-bold">First Name</th>
                      <th className="px-4 py-3 whitespace-nowrap font-bold">Last Name</th>
                      <th className="px-4 py-3 whitespace-nowrap font-bold">Email</th>
                      <th className="px-4 py-3 whitespace-nowrap hidden sm:table-cell font-bold">Permissions</th>
                      <th className="px-4 py-3 text-center whitespace-nowrap font-bold">Action</th>
                    </tr>
                  </thead>
                  <tbody>
                    {editableUsers.map((user, userIndex) => (
                      <tr key={`user-${user.userId}-${userIndex}`} className="border-t border-gray-100 dark:border-slate-700 hover:bg-blue-50 dark:hover:bg-slate-700 transition">
                        <td className="px-4 py-3 align-middle">{user.firstName}</td>
                        <td className="px-4 py-3 align-middle">{user.lastName}</td>
                        <td className="px-4 py-3 align-middle">{user.email}</td>
                        <td className="px-4 py-3 align-middle hidden sm:table-cell">
                          <div className="flex flex-wrap gap-1">
                            {groupPermissions(user.permissions).map((perm, idx) => (
                              <div
                                key={`${user.userId}-${perm}-${idx}`}
                                className="text-xs text-blue-700 dark:text-cyan-300 bg-blue-50 dark:bg-slate-800 px-2 py-1 rounded-lg border border-blue-100 dark:border-slate-700 font-medium mb-1"
                              >
                                {perm}
                              </div>
                            ))}
                          </div>
                        </td>
                        <td className="px-4 py-3 text-center align-middle">
                          <button
                            onClick={() => setSelectedUser(user)}
                            className="w-full sm:w-auto px-4 py-2 bg-blue-600 dark:bg-cyan-700 hover:bg-blue-700 dark:hover:bg-cyan-800 text-white text-xs sm:text-sm rounded-xl font-semibold shadow transition"
                          >
                            Edit
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              {/* Pagination */}
              <div className="flex flex-col sm:flex-row justify-between items-center gap-3 pt-4">
                <button
                  onClick={() => setPage((prev) => Math.max(prev - 1, 0))}
                  disabled={loading || page === 0}
                  className={`w-full sm:w-auto mb-2 sm:mb-0 px-5 py-2 rounded-xl font-medium transition flex items-center justify-center gap-2 ${page === 0 || loading
                    ? 'bg-gray-300 dark:bg-slate-700 text-gray-600 dark:text-gray-400 cursor-not-allowed'
                    : 'bg-blue-600 dark:bg-cyan-700 text-white hover:bg-blue-700 dark:hover:bg-cyan-800'
                    }`}
                >
                  {loading ? (
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                  ) : (
                    'Previous'
                  )}
                </button>
                <button
                  onClick={() => setPage((prev) => prev + 1)}
                  disabled={loading || editableUsers.length < limit}
                  className={`w-full sm:w-auto px-5 py-2 rounded-xl font-medium transition flex items-center justify-center gap-2 ${editableUsers.length < limit || loading
                    ? 'bg-gray-300 dark:bg-slate-700 text-gray-600 dark:text-gray-400 cursor-not-allowed'
                    : 'bg-blue-600 dark:bg-cyan-700 text-white hover:bg-blue-700 dark:hover:bg-cyan-800'
                    }`}
                >
                  {loading ? (
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                  ) : (
                    'Next'
                  )}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
      {/* Edit Modal */}
      {selectedUser && (
        <EditPermission
          user={selectedUser}
          onClose={() => setSelectedUser(null)}
          onSuccess={handlePermissionUpdate}
        />
      )}
    </div>
  );
};

export default UserList;